var app = getApp()
Page({
  data: {
    show: false,
    btn_text: '招领启示',
    lost_thing: {
      _openid: '',
      cloud_imageID: [], //展现页面的data还需要存临时链接
      tempImageUrl: [],
      isLoster: false,
      description: '',
      phone: 0,
      publish_time: 0,
      formId: '',
      time:''
    }
  },
  onLoad() {

  },
  onReady() {
    this.setData({
      show: true
    })
  },
  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.zipImg(0,res.tempFilePaths)
      }
    });
  },
 zipImg(index, tempFilePaths) {
        var that = this
        if (index < tempFilePaths.length) {/////对每一个进行循环，获取连接后写入data
            qq.getImageInfo({
                src: tempFilePaths[index],
                success(res) {
                    //console.log(res)
                    var targetHeight = res.height
                    var targetWidth = res.width
                    var maxWidth = 400
                    var maxHeight = 1000 //2100以内 按宽度1000，高度自适应压缩，
                    //console.log(targetHeight, targetWidth)

                    if (targetWidth > maxWidth || targetHeight > maxHeight) {
                        if ((targetWidth / targetHeight) > (maxWidth / maxHeight)) {
                            targetHeight = Math.round(maxWidth * (targetHeight / targetWidth));
                            targetWidth = maxWidth;
                            // //console.log(">") 顺序什么都不能改变，易错
                        } else {
                            targetWidth = Math.round(maxHeight * (targetWidth / targetHeight));
                            targetHeight = maxHeight;
                        }
                    }
                    //console.log(targetHeight, targetWidth)

                    that.setData({
                        targetWidth: targetWidth,
                        targetHeight: targetHeight,
                        canvasShow: true
                    })
                    setTimeout(function () {
                        const ctx = qq.createCanvasContext('canvas');
                        ctx.drawImage(tempFilePaths[index], 0, 0, targetWidth, targetHeight);
                        ctx.draw(false, function () {
                            qq.canvasToTempFilePath({
                                canvasId: ('canvas'),
                                fileType: "jpg",
                                quality: 0.5,
                                destWidth: targetWidth,
                                destHeight: targetHeight,
                                success(res) {
                                    that.setData({
                                        'lost_thing.tempImageUrl': that.data.lost_thing.tempImageUrl.concat(res.tempFilePath),
                                        canvasShow: false
                                    })
                                    setTimeout(function () {
                                        index++
                                        that.zipImg(index, tempFilePaths);
                                        //console.log(res)
                                    }, 100)
                                }
                            })
                        })
                    }, 100)

                }
            })
        }
    },
  radioChange: function (e) {
    //console.log(e)
    if (e.detail.value == '1') {
      this.setData({
        "lost_thing.isLoster": true,
        btn_text: "寻物启事"
      })
    } else {
      this.setData({
        "lost_thing.isLoster": false,
        btn_text: "招领启示"
      })
    }
  },
  inputDescription(e) {
    this.setData({
      'lost_thing.description': e.detail.value
    })
  },
  inputPhone(e) {
    //console.log(e)
    this.setData({
      'lost_thing.phone': e.detail.value
    })
  },
  doSubmit(e) {
    if (this.data.lost_thing.tempImageUrl.length < 1) {
      qq.showToast({
        icon: 'none',
        title: "请上传图片"
      })
    } else if (this.data.lost_thing.description.length < 3) {
      qq.showToast({
        icon: "none",
        title: "描述信息不少于3个字哦~"
      })
    } else {
        var time = new Date()
      var theTime = time.getFullYear() + '年' + (time.getMonth() + 1) + "月" + time.getDate() + "日 "
      if(time.getHours()<10){
        theTime+='0'
      }
      theTime+=time.getHours()+":"
      if(time.getMinutes()<10){
        theTime+='0'
      }
      theTime+=time.getMinutes()
      this.setData({
        'lost_thing.publish_time': new Date().getTime(),
        'lost_thing._openid': app.globalData.openid,
        'lost_thing.formId': e.detail.formId,
        'lost_thing.time':theTime
      })
      this.uploadFile()
    }
    //console.log(e)
  },
  uploadFile() { ///////////////////////////上传1张图片
    qq.showLoading({
      title: "上传中"
    })
    var that = this
    const filePath = this.data.lost_thing.tempImageUrl[0]
    const cloudPath = 'lost_thing/' + app.globalData.openid + new Date().getTime() + filePath.match(/\.[^.]+?$/)[0]

    var url = 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + app.globalData.access_token
    //console.log(url)
    qq.request({////////////////////////获取cos的url
      url,
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        "env": app.globalData.myEnv,
        "path": cloudPath
      },
      method: "POST",
      success(res) {//////////////////////////通过cos上传
        //console.log(1, res)
        that.data.lost_thing.cloud_imageID=[res.data.file_id]
        qq.uploadFile({
          url: res.data.url,
          filePath,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data"//记得设置
          },
          formData: {
            key: cloudPath,
            "Signature": res.data.authorization,
            "x-cos-security-token": res.data.token,
            "x-cos-meta-fileid": res.data.cos_file_id
          },
          success(res2) { ////////////////////添加到数据库
            //console.log(res2)
            var data = that.data.lost_thing
            //console.log(data)
            that.addToDB(JSON.stringify(data))
          }, fail(msg) {
            //console.log(msg)
          }
        })
        //console.log(res)
      }
    })
  },


  addToDB(data) {
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseadd?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"lost_thing\").add({\
            data: "+ data + "\
        })"
      },
      success(res) {
        qq.hideLoading()
        qq.showToast({
          title: '上传成功！'
        })
        qq.navigateBack()
      }
    })
  },

  ViewImage(e) {
    wx.previewImage({
      urls: this.data.lost_thing.tempImageUrl,
      current: e.currentTarget.dataset.url
    });
  },

  DelImg(e) {
    this.setData({
      'lost_thing.tempImageUrl': []
    })
  },
})